/*
 * Workerthread for communication with the LiveView device
 * @author Robert (xperimental@solidproject.de);
 * This file has been changed by Renze Nicolai (RN+)
 * Image file loader was changed by: basty149
 */
package nl.rnplus.olv.service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import nl.rnplus.olv.messages.LiveViewCall;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

@TargetApi(17)
public class LiveViewSendThread extends Thread {
	
    private static final String TAG = "LiveViewSendThread";

    private LiveViewService parentService;
    private OutputStream outputStream;
    private BlockingQueue<LiveViewCall> sendQueue;

	public LiveViewSendThread(LiveViewService parentService, BluetoothSocket clientSocket) throws IOException {
		super("LiveViewSendThread");
		this.parentService = parentService;
		outputStream = clientSocket.getOutputStream();
		sendQueue = new LinkedBlockingQueue<LiveViewCall>();
	}
	
    /**
     * Send a message to the LiveView device if one is connected.
     *
     * @param call {@link LiveViewCall} to send to device.
     * @throws IOException If the message could not be sent successfully.
     */
    void sendCall(LiveViewCall call) {
    	sendQueue.add(call);
    }
	
    @Override
	public void run() {
        try {
	        do {
        		LiveViewCall call = sendQueue.take();
       	    	outputStream.write(call.getEncoded());
	        } while (true);
        } catch (IOException e) {
            String msg = e.getMessage();
            if (msg.contains("Connection timed out")) {
                Log.e(TAG, "Timed out communicating with LV: " + e.getMessage());
            } else {
                Log.e(TAG, "Error communicating with LV: " + e.getMessage());
            }
            e.printStackTrace();
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted");
        }
        Log.d(TAG, "Stopped LiveView send thread.");

    	parentService.stop();
    }
}
